package org.cainiao.notebook.controller.front.note;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.cainiao.acl.core.annotation.HasScope;
import org.cainiao.api.lark.dto.response.docs.space.folder.LarkFilePage;
import org.cainiao.notebook.dto.CnBlock;
import org.cainiao.notebook.dto.LarkFolderNote;
import org.cainiao.notebook.entity.Note;
import org.cainiao.notebook.service.NoteService;
import org.springframework.security.core.AuthenticatedPrincipal;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

/**
 * 菜鸟笔记是一棵树，每个节点都是菜鸟笔记的数据库记录，节点有多重类型：<br />
 * <ol>
 *     <li>飞书文档，文档中的所有数据来自飞书，菜鸟笔记不入库</li>
 *     <li>飞书文件夹，文件夹中的所有数据来自飞书，菜鸟笔记不入库</li>
 * </ol>
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
@RestController
@RequiredArgsConstructor
@Tag(name = "Note", description = "笔记操作")
public class NoteController {

    private final NoteService noteService;

    @PostMapping("/{id}/notes")
    @Operation(summary = "查询子节点笔记")
    public List<Note> getChildren(
        @AuthenticationPrincipal AuthenticatedPrincipal principal,
        @Parameter(description = "笔记ID") @PathVariable("id") long id) {

        /*
         * DefaultOidcUser 表示已登录的用户，否则视为未登录的匿名用户
         * TODO 已登录的情况暂时只考虑了 OIDC 登录，未考虑用户名密码登录
         */
        return principal instanceof DefaultOidcUser
            ? noteService.getChildren(id, principal.getName()) : Collections.emptyList();
    }

    @PostMapping("/{token}/lark-notes")
    @Operation(summary = "查询飞书子节点笔记")
    @HasScope({"lark"})
    public LarkFilePage getLarkChildren(
        @Parameter(description = "飞书文件夹 Token") @PathVariable("token") String token) {

        return noteService.getLarkChildren(token);
    }

    @PostMapping("/{documentId}/lark-blocks")
    @Operation(summary = "查询飞书文档的所有块")
    @HasScope({"lark"})
    public List<CnBlock> getLarkBlocks(
        @Parameter(description = "文档的唯一标识") @PathVariable("documentId") String documentId) {

        return noteService.getLarkBlocks(documentId);
    }

    @PostMapping("/note/{id}/lark/folder/{folderToken}")
    @Operation(summary = "创建飞书文件夹同步笔记")
    @HasScope({"lark"})
    public LarkFolderNote createLarkFolderNote(
        @AuthenticationPrincipal AuthenticatedPrincipal principal,
        @Parameter(description = "笔记ID，创建的飞书文件夹同步笔记位于这个笔记之下") @PathVariable("id") long id,
        @Parameter(description = "飞书文件夹 Token", required = true) @PathVariable("folderToken") String folderToken) {

        return noteService.createLarkFolderNote(principal.getName(), id, folderToken);
    }
}
